/**
 * liuzy 异步联动控制器
 * 控制联动顺序、控制联动请求的结果需都正常返回才允许流程提交
*/

const orderInfo = {};

//异步联动发请求前调用,生成异步联动key对象，以每个联动设置为维度
//同一个key下多个请求并发，最后一个请求的response才为有效结果
export const generateKeyOrder = (linkageType, reqParams) =>{
    let keyOrder = [];
    const linkageidArr = reqParams.linkageid.split(",");
    linkageidArr && linkageidArr.map(k =>{
        if(k !== ""){
            const rowIndexStr = reqParams["rowIndexStr_"+k] || "-1";
            const keyid = `${linkageType}_${k}_${rowIndexStr}`;
            keyOrder.push({keyid, linkageid:k, orderid:appendOrderInfo(keyid)});
        }
    });
    return keyOrder;
}

//生成顺序
const appendOrderInfo = (key) => {
    if(key in orderInfo)
        orderInfo[key].index++;
    else
        orderInfo[key] = {index:0};
    orderInfo[key].time = new Date().getTime();
    orderInfo[key].finished = false;
    return orderInfo[key].index;
}

//联动结果response赋值前调用，移除无效的结果
export const removeInvalidResponse = (keyOrder, resData) =>{
    keyOrder.map(item =>{
        const { keyid,linkageid,orderid } = item;
        if(orderid >= orderInfo[keyid].index){  //最新请求的response
            orderInfo[keyid].finished = true;
        }else{      //先发后置的无效response
            if(`assignInfo_${linkageid}` in resData)
                delete resData[`assignInfo_${linkageid}`];
        }
    });
    return resData;
}

//流程提交时调用，判断异步联动结果是否都正常返回
//如果存在联动未返回，定时器扫描等待，超过2s给提示信息，超过10s作为联动失败处理允许继续提交
export const verifyLinkageFinished = (callback) =>{
    try{
        let hasNotice = false;
        const timer = window.setInterval(function(){
            let linkageBegTime = "";
            for(const key in orderInfo){
                if(!orderInfo[key].finished){
                    linkageBegTime = orderInfo[key].time;
                    break;
                }
            }
            const submitBegTime = new Date().getTime();
            if(linkageBegTime === "" || submitBegTime - linkageBegTime > 10*1000){
                window.clearInterval(timer);
                callback();
            }else if(submitBegTime - linkageBegTime > 2*1000 && !hasNotice){
                window.WfForm.showMessage("存在联动请求未返回，请耐心等待...");
                hasNotice = true;
            }
        }, 200);
    }catch(e){
        callback();
    }
}